home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!sun2!ua302aa
- From: ua302aa@sun2.lrz-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: start array at k, not 0
- Date: 4 Jan 1996 19:20:23 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4ch99n$ick@sparcserver.lrz-muenchen.de>
- References: <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- Bill Simpson <wsimpson@uwinnipeg.ca> writes:
-
- >I have come up with the following 2 methods that allow one to talk about
- >an array that starts at element k rather than 0. E.g. 10 element array
- >y[k] to y[k+10]. Both seem to work. Is this illusory? Is one of the
- >2 ways better (or a way I haven't mentioned)?
-
- >These programs set up y[5] to y[14].
-
- >Thanks very much for any comments.
-
- >Bill Simpson
-
- >/*method 1*/
- >#include <stdio.h>
-
- >int main(void)
- > {
- > int i, x[10];
- > int* y;
- > int offset=5; /*ie 1st index at 5, y[5]-y[14] */
- > y=x-offset;
-
- You performed pointer arithmetic that led you outside array bounds,
- so from now on anything can happen. "x - 1 < x" need not be true.
-
- > printf("offset=%d\n",offset);
-
- > for (i=offset;i<10+offset;i++)
- > {
- > y[i]=i;
- > printf("%d\n",y[i]);
- > }
- > return 0;
- > }
-
- >/*method 2*/
- >#include <stdio.h>
- >#include <stdlib.h>
-
- >int main(void)
- > {
- > int i;
- > int* y;
- > int offset=5;
- > int n=10;
- > y=malloc(n*sizeof(int));
-
- > printf("offset=%d\n",offset);
-
- > for (i=offset;i<n+offset;i++)
- > {
- > y[i]=i;
- > printf("%d\n",y[i]);
- > }
- > return 0;
- > }
-
- Now you access memory that has not been allocated, or may memory
- that has been allocated, but for a different purpose. While pointer
- arithmetic referring to "x + 10" is well defined, storing anything
- through that pointer is not.
-
- If you absolutely _have to_ have arrays with a positive offset
- greater than 0 in C, allocate the memory you need and waste
- some bytes at the beginning of the array:
-
- int y[15];
-
- Now you can do whatever you want with y[5], ..., y[14].
-
- BTW, in most cases it is possible to work with 0 based arrays,
- imho. If you absolutely need a different base, try to hide
- access to array elements behind a set of macros that take your
- offset into account.
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
- | ua302aa@sunmail.lrz-muenchen.de
-